package ThreadPoolTest;

import com.github.pagehelper.util.StringUtil;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolWithRedisDlqExample {
    public static void main(String[] args) {

        RedisDlqManager redisDlqManager = new RedisDlqManager("localhost", 6379);

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                1,
                1,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1),
                new RedisDlqDiscardPolicy(redisDlqManager));



                for (int i=1 ;i<=10;i++){
                    String taskId = "task" +   i;
                    executor.execute(()->{
                        System.out.println("执行任务" + taskId);

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    });
                }


                //启动死信队列执行任务
                new Thread(()->{
                    while(true){
                        String taskInfo = redisDlqManager.takeTask();
                        if (StringUtil.isNotEmpty(taskInfo)){
                            System.out.println("从Redis死信队列重新处理任务:" + taskInfo);
                        }

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                    }
                }).start();



        executor.shutdown();

//        try {
//            if (!executor.awaitTermination(1000,TimeUnit.SECONDS)){
//                executor.shutdownNow();
//            }
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

        // 程序结束前关闭Redis连接
        Runtime.getRuntime().addShutdownHook(new Thread(redisDlqManager::close));


    }

}
